/*************************************************************************
    > File Name: 1.process_tcp_server.c
    > Author: Ykk
    > Mail: 3393579535@qq.com 
    > Created Time: 2023年05月18日 星期四 20时20分26秒
 ************************************************************************/

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<errno.h>
void free_process(int sig)
{
	pid_t pid;
	while(1)
	{
		pid = waitpid(-1,NULL,WNOHANG);
		if(pid <= 0)//小于0 子进程全部退出  =0 没有进程没有退出
		{
			break;
		}
		else
		{
			printf("child pid = %d\n",pid);
		}	
	}
}
int main()
{
	sigset_t set;
	sigemptyset(&set);
	sigaddset(&set,SIGCHLD);
	sigprocmask(SIG_BLOCK,&set,NULL);
	//创建套接字
	int n = -1;
	int lis_fd = socket(AF_INET,SOCK_STREAM,0);
	if(-1 == lis_fd)
	{
		perror("socket");
	}
	else
	{
		printf("创建套接字成功...\n");
	}
	//绑定
	struct sockaddr_in addr;
	bzero(&addr,sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(8000);
	n = inet_pton(AF_INET,"192.168.152.129",&addr.sin_addr.s_addr);
	if(n <= 0)
	{
		perror("ip");
	}

	n = bind(lis_fd,(struct sockaddr *)&addr,sizeof(addr));
	if( -1 == n)
	{
		perror("bind");
	}
	else
	{
		printf("绑定成功");
	}
	//监听
	n = listen(lis_fd,128);
	if(-1 == n)
	{
		perror("listen");
	}
	else
	{
		printf("监听成功...\n");
	}
	//提取  回射
	struct sockaddr_in cli_addr;
	int cli_fd;
	while(1)
	{
		char ip[16]="";
		socklen_t len = sizeof(cli_addr);
		cli_fd = accept(lis_fd,(struct sockaddr *)&cli_addr,&len);
		if(-1 == cli_fd)
		{
			if(errno == EINTR)
			{
				continue;
			}
			perror("accept");
		}
		else
		{
			printf("client:%s,port:%d连接成功...\n",inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,ip,16),
					                                ntohs(cli_addr.sin_port));
		}
		//fork创建子进程
		pid_t pid;
		pid = fork();
		if(pid < 0)
		{
			perror("fork");
			exit(0);
		}
		else if(pid == 0)//子进程
		{
			close(lis_fd);
			while(1)
			{
				char buf[1024]="";
				bzero(buf,sizeof(buf));
				int a = read(cli_fd,buf,sizeof(buf));
				if(a < 0)
				{
					perror("read");
	
					close(cli_fd);

					exit(0);
				}
				else if(a == 0)
				{
				
					printf("client:%s port:%d  close...\n",inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,ip,16),
				                                	ntohs(cli_addr.sin_port));

					close(cli_fd);

					exit(0);	
				}
				else
				{
					printf("%sport:%d==>%s\n",inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,ip,16),
					                  ntohs(cli_addr.sin_port),buf);

					write(cli_fd,buf,a+sizeof(ip)+4);
				}
			}
		}
		else//父进程
		{
			close(cli_fd);
			//回收
			
			//注册信号回调
			struct sigaction act;
			act.sa_flags = 0;
			act.sa_handler = free_process;
			sigemptyset(&act.sa_mask);
			sigaction(SIGCHLD,&act,NULL);
			sigprocmask(SIG_UNBLOCK,&set,NULL);
		}
	}
	//关闭
	close(lis_fd);
}
